package com.capgemini.cn.authority.data.entity;

import com.capgemini.cn.authority.data.core.BaseEntity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.List;

/**
 * <p>用户组表</p>
 * Created at 2017/8/21
 *
 * @author Andriy
 */
@Entity
@Table(name = "cg_groups")
@NoArgsConstructor
@AllArgsConstructor
public class Groups extends BaseEntity {

    /**
     * 用户组名称
     */
    @Column(name = "group_name", length = 50, nullable = false)
    @Getter
    @Setter
    private String groupName;

    /**
     * 父用户组
     */
    @ManyToOne(targetEntity = Groups.class, fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_group_id")
    @Getter
    @Setter
    private Groups parentGroup;

    /**
     * 所属用户组组织架构中的根用户组
     */
    @Column(name = "root_group_id")
    @Getter
    @Setter
    private long rootGroupId;

    /**
     * 业务数据标识，当前主要目的是用于在自动同步分组数据时用以标识对应业务数据的唯一性
     */
    @Column(name = "biz_identity", unique = true)
    @Getter
    @Setter
    private String bizIdentity;

    /**
     * 当前用户组的所有子集
     */
    @OneToMany(mappedBy = "parentGroup", targetEntity = Groups.class, cascade = {
            CascadeType.REMOVE
    })
    @Getter
    @Setter
    private List<Groups> childrenGroups;

    /**
     * 用户组成员集合
     */
    @OneToMany(targetEntity = GroupMembers.class)
    @JoinColumn(name = "group_id")
    @Getter
    @Setter
    private List<GroupMembers> groupMembers;

    /**
     * <p>角色与用户组的多对多关系</p>
     * <p>关系维护者为{@link Roles}对象，即对应的用户组被删除时相应的小组关联的角色关系也会一并被解除，反之移除对应的角色数据之前需先手动解除角色与用户组数据的关系</p>
     */
    @ManyToMany(targetEntity = Roles.class, cascade = {
            CascadeType.REMOVE
    })
    @JoinTable(name = "cg_roles_members", joinColumns = {
            @JoinColumn(name = "group_id", referencedColumnName = "id", nullable = false, updatable = false)
    }, inverseJoinColumns = {
            @JoinColumn(name = "role_id", referencedColumnName = "id", nullable = false, updatable = false)
    })
    @Getter
    @Setter
    private List<Roles> roles;

    /**
     * 创建用户组构造函数
     *
     * @param groupName 用户组名
     */
    public Groups(String groupName) {
        this.groupName = groupName;
    }
}
